<template>
    <page-wrap :loading="loading">
        <div class="orderMember-container">
            <div class="orderMember-main">
                <div class="orderMember-card" v-show="memberData.cardType == 1">
                    <div class="orderMember-card-corner">
                        <div class="card-corner-no">{{ memberData.code }}</div>
                        <div class="card-header-change" v-if="canChange" @click.stop="cardChange(memberData.cardType)">
                            <div class="icon"></div>切换{{ memberData.cardType == 1 ? '门店' : '品牌' }}卡
                        </div>
                    </div>
                    <div class="orderMember-card-heading">
                        <div class="orderMember-card-heading__name">{{ memberData.name }}</div>
                        <img class="orderMember-card-heading__level" :src="i_member_level" alt="SVG Icon" />
                    </div>
                    <div class="orderMember-card-money">
                        <div class="orderMember-card-money__num">{{ formatDecimal(memberData.currentAmtAct) }}</div>
                        <div class="orderMember-card-money__label" @click="showAmt">账户余额
                            <div class="value-icon"></div>
                            <div class="showAmt" v-show="isShowAmt">
                                <div class="showAmt-top">
                                <div class="showAmt-top-value">{{ formatDecimal(memberData.currentAmtAct) }}</div>
                                <div class="showAmt-top-title">总余额</div>
                                </div>
                                <div class="showAmt-main">
                                <div class="showAmt-main-value">本金金额：{{ formatDecimal(memberData.currentAmt)}} </div>
                                <div class="showAmt-main-value">赠送金额：{{ formatDecimal(memberData.currentPresentAmt)}} </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="orderMember-card-line"></div>
                    <div class="orderMember-card-footer">
                        <div class="orderMember-card-footer-item">
                            <div class="orderMember-card-footer__num">{{ formatDecimal(memberData.currentCoins) }}</div>
                            <div class="orderMember-card-footer__label">账户金币</div>
                        </div>
                        <div class="orderMember-card-footer-item" style="border: none;">
                            <div class="orderMember-card-footer__num">{{ memberData.currentPoint }}</div>
                            <div class="orderMember-card-footer__label">账户积分</div>
                        </div>
                    </div>
                </div>
                <div class="orderMember-card1" v-show="memberData.cardType == 2">
                    <div class="orderMember-card1-corner">
                        <div class="card1-corner-no">{{ memberData.code }}</div>
                        <div class="card1-header-change" v-if="canChange" @click.stop="cardChange(memberData.cardType)">
                            <div class="icon"></div>切换{{ memberData.cardType == 1 ? '门店' : '品牌' }}卡
                        </div>
                    </div>
                    <div class="orderMember-card1-heading">
                        <div class="orderMember-card1-heading__name">{{ memberData.name }}</div>
                        <img class="orderMember-card1-heading__level" :src="i_member_level" alt="SVG Icon" />
                    </div>
                    <div class="orderMember-card1-money">
                        <div class="orderMember-card1-money__num">{{ formatDecimal(memberData.currentAmtAct) }}</div>
                        <div class="orderMember-card1-money__label" @click="showAmt">账户余额
                            <div class="value-icon"></div>
                            <div class="showAmt" v-show="isShowAmt">
                                <div class="showAmt-top">
                                <div class="showAmt-top-value">{{ formatDecimal(memberData.currentAmtAct) }}</div>
                                <div class="showAmt-top-title">总余额</div>
                                </div>
                                <div class="showAmt-main">
                                <div class="showAmt-main-value">本金金额：{{ formatDecimal(memberData.currentAmt)}} </div>
                                <div class="showAmt-main-value">赠送金额：{{ formatDecimal(memberData.currentPresentAmt)}} </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="orderMember-card1-line"></div>
                    <div class="orderMember-card1-footer">
                        <div class="orderMember-card1-footer-item">
                            <div class="orderMember-card1-footer__num">{{ formatDecimal(memberData.currentCoins) }}</div>
                            <div class="orderMember-card1-footer__label">账户金币</div>
                        </div>
                        <div class="orderMember-card1-footer-item" style="border: none;">
                            <div class="orderMember-card1-footer__num">{{ memberData.currentPoint }}</div>
                            <div class="orderMember-card1-footer__label">账户积分</div>
                        </div>
                    </div>
                </div>
                <div class="orderMember-form">
                    <!-- <div class="orderMember-form-recharge">
                        <div class="orderMember-form-recharge__title">使用余额支付</div>
                        <div class="orderMember-form-recharge__item">
                            <div class="orderMember-form-recharge__rmb">￥</div>
                            <input type="text" class="orderMember-form-recharge__input" placeholder="请输入金额" v-model="(payListForm.payAmt)" />
                            <div class="orderMember-form-recharge__btn" @click="rechargeCodeShow = true">充值</div>
                        </div>
                    </div> -->
                    <div class="orderMember-form-heading">
                        本次消费可获得<span class="orderMember-form-heading__highlight">{{ formatDecimal(payListForm.payAmt *
                            memberData.pointsRate) }}</span>积分
                    </div>
                    <div class="orderMember-form-radio">
                        <!-- <van-radio-group v-model="formCheck" disabled @click="onCheckDiscount"> -->
                        <!-- <van-radio class="orderMember-form-radio-item" name="1">
                                使用金币支付
                                <template #icon="props">
                                    <img class="orderMember-form-radio__icon" :src="formCheck==1?v_radio_checked:v_radio_check" alt="SVG Icon" />
                                </template>
                            </van-radio> -->
                        <div class="radio-coupon">
                            <!-- <van-checkbox class="orderMember-form-radio-item" v-model="couponChecked"
                                @change="onChangeCoupon">
                                使用优惠券
                                <template #icon="props">
                                    <img class="orderMember-form-radio__icon"
                                        :src="couponChecked ? v_radio_checked : v_radio_check" alt="SVG Icon" />
                                </template>
                            </van-checkbox> -->
                            <div class="ticket-box">
                                <img class="img-ticket" src="@/assets/images/member/ticket.png" alt="">
                                <div>优惠券</div>
                            </div>
                            <div class="orderMember-form-radio__popover" @click="onSelectTicket">
                                <div class="orderMember-form-radio__select">已抵扣：￥{{ formatDecimal(ticketValue) }}</div>
                            </div>

                            <!-- </van-radio-group> -->
                            <!-- <van-popover 
                                class="orderMember-form-radio__popover"
                                v-model:show="showTickets" 
                                :actions="ticketActions"
                                theme="dark" 
                                placement="bottom-end" 
                                @select="onCheckTicket" 
                                overlay 
                                :overlay-style="{
                                    background: 'transparent'
                                }"
                                >
                                    <template #reference>
                                        
                                    </template>
                                </van-popover> -->
                        </div>
                        <div class="radio-coupon-list" v-for="(v, k) in checkedList" :key="k">
                            <div class="list-item">{{ v.TicketName }}</div>
                            <div class="list-icon" @click="delCoupon(k)">×</div>
                        </div>
                        <div class="radio-coupon">
                            <div class="ticket-box">
                                <img class="img-ticket" src="@/assets/images/member/coins.png" alt="">
                                <div>金币</div>
                            </div>
                            <div class="orderMember-form-radio__popover" @click="onSelectCoins">
                                <div class="orderMember-form-radio__select">已抵扣：￥{{ formatDecimal(coinsValue) }}</div>
                            </div>
                        </div>
                        <div class="stay-box">
                            <!-- 待付金额：￥<span class="color-FFAA00 font-size-18">{{ formatDecimal(stayPay)}}</span> -->
                            待付金额：￥<span class="color-FFAA00 font-size-18">{{ formatDecimal(showPayAmt)}}</span> 
                        </div>
                        <!-- <div class="radio-cardPay">
                                <van-checkbox class="orderMember-form-radio-item" v-model="isMemberPrice" @change="onChangeMemPri">
                                    享受会员优惠
                                    <template #icon="props">
                                        <img class="orderMember-form-radio__icon" :src="isMemberPrice?v_radio_checked:v_radio_check" alt="SVG Icon" />
                                    </template>
                                </van-checkbox>
                            </div> -->

                    </div>

                    <van-checkbox class="usevip-box orderMember-form-radio-item" v-model="memberPay"
                        @change="onChangeMemberPay">
                        使用会员卡支付
                        <template #icon="props">
                            <img class="orderMember-form-radio__icon" :src="memberPay ? v_radio_checked : v_radio_check"
                                alt="SVG Icon" />
                        </template>
                    </van-checkbox>
                    <div class="radio-input">
                        <div class="radio-input-icon">￥</div>
                        <input type="number" class="orderMember-form-recharge__input" placeholder="请输入金额"
                            v-model="payListForm.payAmt" />
                        <div class="radio-input-yuan">元</div>
                        <!-- <div class="radio-input-title">其中金币抵扣<span class="spe">15.00</span>元</div> -->
                    </div>
                </div>
            </div>
            <div class="orderMember-footer">
                <div class="orderMember-footer-value">待支付：<span class="value-icon">￥</span><span class="value-money">{{
                    formatDecimal(showPayAmt) }}</span></div>
                <div>
                    <z-button @click="onPay" v-has-role="'waiter-checkout-membercard'" style="padding-left: 15px;padding-right: 15px;">确认使用</z-button>
                </div>
            </div>
        </div>
    </page-wrap>

    <!-- 会员充值码弹窗 -->
    <RechargeCode v-model:show="rechargeCodeShow" />

    <!-- 会员充值成功弹窗 -->
    <z-popup v-model:show="payShow" :close-on-click-overlay="false">

        <div class="popup-pay" v-if="payIsWhole">
            <div class="popup-pay-success">会员卡支付成功</div>
            <div class="popup-pay-control finish">
                <z-button>完成</z-button>
            </div>
        </div>
        <div class="popup-pay" v-else>
            <div class="popup-pay-title">会员卡支付成功</div>
            <div class="popup-pay-unpaid">
                剩余<span class="popup-pay__hightlight">{{ cartStore.unpaid }}元</span>订单待支付
            </div>
            <div class="popup-pay-control goon">
                <z-button @click="onContinueToPay">继续支付</z-button>
            </div>
        </div>
    </z-popup>

    <z-popup v-model:show="showTickets" position="bottom" :close-on-click-overlay="false">
        <div class="showTickets">
            <z-tab v-model:active="tabTicketsActive" :tabList="showTicketsList" top="13" @click-tab="setActive"></z-tab>
            <div class="showTickets-list" v-show="tabTicketsActive == 0">
                <div class="showTickets-list-item" v-for="(v, k) in canUseCouponList" :key="k"
                    @click.stop="selectCoupon(v)">
                    <div class="item-left"
                        :class="{ huang: v.TypeCodeName == '兑换券', zhe: v.TypeCodeName == '折扣券', you: v.TypeCodeName == '优惠券' }">
                        <div class="coupon-left">
                            <div class="coupon-left-title">{{ v.TypeCodeName }}</div>
                            <div class="coupon-left-value">{{ v.TicketName }}</div>
                        </div>
                        <div class="coupon-center">
                            <div class="coupon-center-top">有效期：{{ dayjs(v.EndData).format('YYYY-MM-DD HH:mm') }}</div>
                            <div class="coupon-center-center" v-if="v.TypeCodeName == '兑换券'">兑换物品：{{ v.GoodsName }}</div>
                            <div class="coupon-center-center" v-if="v.TypeCodeName == '折扣券'">{{ v.TicketName }}</div>
                            <div class="coupon-center-center" v-if="v.TypeCodeName == '优惠券'">{{ v.TicketAmt }}元</div>
                            <div class="coupon-center-bottom" v-if="v.UseCondition == '1'">
                                <!-- 1 桌台限制  2 会员限制 0 无限制 -->
                                使用限制：单桌台可同时使用{{ v.RoomUseNum }}张
                            </div>
                            <div class="coupon-center-bottom" v-if="v.UseCondition == '2'">
                                <!-- 1 桌台限制  2 会员限制 0 无限制 -->
                                使用限制：单次消费可用{{ v.MemberUseNum }}张
                            </div>
                            <div class="coupon-center-bottom" v-if="v.UseCondition == '0'">
                                <!-- 1 桌台限制  2 会员限制 0 无限制 -->
                                无使用限制
                            </div>
                        </div>
                        <div class="coupon-right" v-if="v.IsNew">
                        </div>
                    </div>
                    <div class="item-right">
                        <van-checkbox class="orderMember-form-radio-item" v-model="v.checked" readonly disabled>
                            <template #icon="props">
                                <img class="orderMember-form-radio__icon"
                                    :src="v.checked ? v_radio_Zchecked : v_radio_Zcheck" alt="SVG Icon" />
                            </template>
                        </van-checkbox>
                    </div>
                </div>

            </div>
            <div class="showTickets-list" v-show="tabTicketsActive == 1">
                <div class="showTickets-list-item canNotUse" v-for="(v, k) in canNotCouponList" :key="k">
                    <div class="item-left">
                        <div class="coupon-left">
                            <div class="coupon-left-title">{{ v.TypeCodeName }}</div>
                            <div class="coupon-left-value">{{ v.TicketName }}</div>
                        </div>
                        <div class="coupon-center">
                            <div class="coupon-center-top">有效期：{{ dayjs(v.EndData).format('YYYY-MM-DD HH:mm') }}</div>
                            <div class="coupon-center-center" v-if="v.TypeCodeName == '兑换券'">兑换物品：{{ v.GoodsName }}</div>
                            <div class="coupon-center-center" v-if="v.TypeCodeName == '折扣券'">{{ v.Discounts }}</div>
                            <div class="coupon-center-center" v-if="v.TypeCodeName == '优惠券'">{{ v.TicketAmt }}元</div>
                            <div class="coupon-center-bottom" v-if="v.UseCondition == '1'">
                                <!-- 1 桌台限制  2 会员限制 0 无限制 -->
                                使用限制：单桌台可同时使用{{ v.RoomUseNum }}张
                            </div>
                            <div class="coupon-center-bottom" v-if="v.UseCondition == '2'">
                                <!-- 1 桌台限制  2 会员限制 0 无限制 -->
                                使用限制：单次消费可用{{ v.MemberUseNum }}张
                            </div>
                            <div class="coupon-center-bottom" v-if="v.UseCondition == '0'">
                                <!-- 1 桌台限制  2 会员限制 0 无限制 -->
                                无使用限制
                            </div>
                        </div>
                        <div class="coupon-right" v-if="false">
                        </div>
                    </div>
                    <!-- <div class="item-right">
                        <van-checkbox class="orderMember-form-radio-item" v-model="v.checked">
                            <template #icon="props">
                                <img class="orderMember-form-radio__icon" :src="v.checked?v_radio_Zchecked:v_radio_Zcheck" alt="SVG Icon" />
                            </template>
                        </van-checkbox>
                    </div> -->
                </div>

            </div>
            <div class="showTickets-bottom">
                <div class="showTickets-bottom-cancle" @click="couponCancle">取消</div>
                <div class="showTickets-bottom-confirm" @click="couponConfirm">确认</div>
            </div>
        </div>
    </z-popup>
    <PopupCoins ref="CoinsRef" v-if="CoinsVisible" :visible="CoinsVisible" :memberData="memberData" :coinsTotal="coinsTotal"
        @emitCancel="emitCoinsCancel" @emitSubmit="emitCoinsSubmit"></PopupCoins>
</template>
<script setup>
import { showToast } from 'vant';
import useCartStore from '@/store/cart'
import Api from '@/api'
import ls from '@/lib/ls'
import dayjs from 'dayjs';
import useConfigStore from '@/store/config'

import v_radio_check from '@/assets/svg/common/v_radio_check.svg'
import v_radio_checked from '@/assets/svg/common/v_radio_checked.svg'
import v_radio_Zcheck from '@/assets/svg/common/v_radio_Zcheck.svg'
import v_radio_Zchecked from '@/assets/svg/common/v_radio_Zchecked.svg'
import i_member_level from '@/assets/images/open/i_member_level.png'
import i_qrcode_recharge from '@/assets/images/common/i_qrcode_recharge.png'
import { formatDecimal,calculateOrderQty } from '@/lib/util.js'
import { rule_share, rule_amt, rule_count, returnCheckedTicket, table_use, menber_use, count_use } from './ticketRules' // 优惠券使用方法
import PopupCoins from "./PopupCoins.vue"
const cartStore = useCartStore()
const configStore = useConfigStore()
const router = useRouter()

const formCheck = ref(0)
const showTickets = ref(false)
const ticketValue = ref(0)
const rechargeCodeShow = ref(false)
const payShow = ref(false)
const payIsWhole = ref(false)
const memberData = ref({}) // 会员卡显示数据
const memberDataList = ref([]) // 会员卡数组
const totalAmount = ref(0)
const stayPay = ref(0) //代付金额
const coinsTotal = ref(0)
let coinDiko = ref(0)
const loading = ref(false)
const postForm = reactive({
    // 消费单号
    consumeCode: '',
    // 房台编码
    roomCode: '',
    // 付款人(代付)，（服务员）
    payUser: '',
    // 批次号(首次买单为空,后续再买单将首次的批次号传入)
    payBatchCode: '',
    // 收银员 - 传空
    cashUser: '',
    // 付款商品列表(使用点单的itemCode)
    detailList: '',
    // 商品单号
    tradeNo: '',
    // 使用会员券编码
    memberTicketCode: '',
    // detailList: cartStore.goodsOrderStr,
    // 点单商品金额
    orderAmt: '',
    // 实际收款金额
    realPayAmt: '',
    // 支付方式(001现金 002微信 003支付宝 004会员卡 005消费卷 006银联 007其他 008挂账 009聚合支付 010团购券 011赠送 012会员优惠券)
    payType: '',
    /*
     * 支付列表(手机端只有一条,电脑端可能有多条)
     * @totalAmt 本条的付款金额
     * @payAmt 客人付款金额(现金可能大于点单金额,需要有找零和抹零,其他方式totalAmt == payAmt)
     * @giveChange 找零金额
     * @smallChange 抹零金额
     * @cardNo 会员编码(会员付款) - 传空
     * @memberName 会员姓名 - 传空
     * @memberMobile 电话 - 传空
     * @memberOpenId openid - 传空
     * @payType 支付方式(001 现金002微信003支付宝004会员卡005消费卷)
     */
    payList: [],
    /*
     *"code": "买单批次号",
     *"type": "抹零/服务费/折扣优惠/补低消",
     *"subType": "子类型",
     *"amt": "服务费类型"
    */
    serviceAmt: [] // 优惠项目
})
const showPayAmt = computed(() => Number(stayPay.value) - Number(coinDiko.value) - Number(ticketValue.value) ) // 代付金额-金币抵扣-优惠券优惠
const toolPayAmt = ref(0) // 工具价格(用来记录减去优惠券和金币前的价格)
watch(showPayAmt, (newValue, oldValue) => {
    payListForm.payAmt = toolPayAmt.value
    payListForm.payAmt = formatDecimal(payListForm.payAmt - Number(coinDiko.value) - Number(ticketValue.value) - Number(bookAmt.value))
    console.log(newValue);
    if(newValue >0){
        memberPay.value = true
    }else{
        memberPay.value = false
    }
    
});

// 支付列表(手机端只有一条,电脑端可能有多条)
const payListForm = reactive({
    // 本条的付款金额
    totalAmt: '',
    // 客人付款金额（现金可能大于点单金额,需要有找零和抹零,其他方式totalAmt == payAmt）
    payAmt: '',
    // 找零金额
    giveChange: '',
    // 抹零金额
    smallChange: '',
    // 会员编码（会员付款）
    cardNo: '',
    // 会员姓名
    memberName: '',
    // 电话
    memberMobile: '',
    // openid
    memberOpenId: '',
    // 支付方式（001现金 002微信 003支付宝 004会员卡 005消费卷）
    payType: '',
    // 找赎金额(现金支付需要传)
    notGiveChange: '',
    // 挂账人名称(挂账支付需要传)
    mountUser: '',
    // 挂账人手机号(挂账支付需要传
    mountMobile: '',
    // 挂账人性别(字典数据编号011)(挂账支付需要传)
    mountSex: '',
    // 担保人编号,服务员数据(挂账支付需要传)
    suretyUser: '',
    // 赠送人服务员数据(赠送支付需要传)
    giftUser: '',
    // 赠送备注(赠送支付需要传)
    giftRemark: ''

})
const serviceAmtForm = ref({
    code: '',
    type: '',
    subType: '',
    amt: ''
})

// ------------------------------------------------- 优惠券 -----------------------------------------------------
const tabTicketsActive = ref(0)
const showTicketsList = ref([{
    name: '可使用优惠券(0)'
},
{
    name: '不可用优惠券(0)'
}])
// 优惠券tab切换
const setActive = (e) => {
    tabTicketsActive.value = e.name
    console.log(tabTicketsActive.value);
}
const couponChecked = ref(false) // 是否使用优惠券
let memberPay = ref(true) // 是否使用会员卡支付
const isMemberPrice = ref(false)
const canUseCouponList = ref([]) // 可用优惠券list
const canNotCouponList = ref([]) // 不可用优惠券
const usedTickets = ref([]) // 返回的TicketUseList
const selectWares = ref([]) // 本次消费的商品列表
const checkedList = ref([]) // 选中的券的数组
const checkedAmt = ref(0) // 优惠券可抵扣金额
const roomuselist = ref([])
const ticketUseTypeList = ref([])
let goodsTicketList = ref([]) // 本单可用兑换券的商品数组
// 是否使用优惠券
const onChangeCoupon = (e) => {
    console.log(couponChecked.value);
}
// 是否使用会员卡支付
const onChangeMemberPay = (e)=>{
    console.log(memberPay.value);
}
const isShowAmt = ref(false)
const showAmt = ()=>{
  isShowAmt.value = true
  setTimeout(() => {
    isShowAmt.value = false
    }, 2000); // 2秒后隐藏提示
}
// 是否享受会员价
const onChangeMemPri = (e) => {
    console.log(isMemberPrice.value);
}
const convertObjectKeysToLowercase = (obj) => {
    if (Array.isArray(obj)) {
        return obj.map(item => convertObjectKeysToLowercase(item));
    } else if (typeof obj === 'object' && obj !== null) {
        return Object.fromEntries(
            Object.entries(obj).map(([key, value]) => [
                key.charAt(0).toLowerCase() + key.slice(1),
                convertObjectKeysToLowercase(value)
            ])
        );
    } else {
        return obj;
    }
}
// 获取优惠券
const onSelectTicket = function () {
    if (stayPay.value <= 0) {
        showToast('待支付金额为0')
        return
    }
    checkedList.value = []
    showTickets.value = true
    isVip.value = false
    if(memberData.value.memberIsPayCard == 1){
        isVip.value = true
    }
    const postForm = {
        memberCarCode: memberData.value.code,
        consumeCode: ls.get('TABLE_INFO').consumeCode,
        orderDetails: JSON.stringify(selectWares.value),
        isVip: isVip.value
    }
    Api.Common.AppObjProcess.Do({
        "functionName": "GetUseMemberTicket",
        "contentData": postForm
    }).then(res => {
        console.log('获取优惠券列表', res);
        // 可用兑换券添加
        goodsTicketList.value = res.OrderStatistics
        goodsTicketList.value.forEach(v=>{
            v.isCanUseMore = true // 可以使用兑换券优惠券
        })  
        res.TicketList = res.TicketList.map(item => {
            return {
                ...item, // 复制原始对象的属性
                checked: false // 添加新的属性，并设置初始值为 false
            };
        })
        console.log(res.TicketList);
        roomuselist.value = res.roomuselist
        ticketUseTypeList.value = res.ticketUseTypeList
        usedTickets.value = res.TicketUseList
        canUseCouponList.value = res.TicketList.filter(item => item.IsUse)
        canNotCouponList.value = res.TicketList.filter(item => item.IsUse == false)
        let UseCouponLength = canUseCouponList.value.length
        let NotCouponLength = canNotCouponList.value.length
        // canUseCouponList.value = res.TicketList
        showTicketsList.value = [{
            name: `可使用优惠券(${UseCouponLength})`
        },
        {
            name: `不可用优惠券(${NotCouponLength})`
        }]


    })
}
// 点击优惠券
const selectCoupon = (item, e) => {

    console.log(item, e);
    // 判断如果是取消勾选就不进入之后的验证
    if (item.checked) {
        item.checked = !item.checked
        checkedAmt.value -= (+item.deductionAmt)
        checkedList.value.forEach((i, $index) => {
            if (i.code == item.code) {
                checkedList.value.splice($index, 1);
            }
        })
        // 兑换券
        goodsTicketList.value.forEach(v=>{
            if(v.goodsCode == item.goodsCode){
                v.orderQty += Number(item.goodsCount)
                if(v.orderQty > 0){
                    v.isCanUseMore = true
                }
                
            }
        })

        console.log('checkedList.value :>> ', checkedList.value);
        return
    }
    let couponAmt = 0
    // 使用优惠券时 要判断是否用了金币和金币的
    checkedList.value.forEach(item => {
        console.log(item.TicketAmt);
        couponAmt += Number(item.deductionAmt)
    })
    if( Number(couponAmt) >= Number(stayPay.value) - Number(coinDiko.value) ){
        showToast('优惠券金额已超出待付金额')
        return  
    }
    // 判断兑换券是否可用
    goodsTicketList.value.forEach(v=>{
        if(v.goodsCode == item.goodsCode && !v.isCanUseMore){
            showToast('兑换券使用数量已到上限')
            return   
        }
    })
    //  checkedList.value, ticketUseList.value, ticketUseTypeList.value
    // 验证优惠共享
    // console.log(' router.currentRoute.value.query.memberPrice :>> ', router.currentRoute.value.query.memberPrice);
    const rule_share_res = rule_share(item, checkedList.value, roomuselist.value, router.currentRoute.value.query.memberPrice)
    // console.log('rule_share_res :>> ', rule_share_res);
    if (!rule_share_res.flag) return showToast(rule_share_res.errMsg)
    // 验证 金额限制条件 不限制 满 每满
    const rule_amt_res = rule_amt(item, checkedList.value, roomuselist.value, usedTickets.value,)
    // console.log('rule_amt_res :>> ', rule_amt_res);
    if (!rule_amt_res.flag) return showToast(rule_amt_res.errMsg)

    // 验证桌台或者会员使用数量
    const rule_count_res = rule_count(item, checkedList.value, usedTickets.value, ticketUseTypeList.value)
    console.log('rule_count_res :>> ', rule_count_res);
    if (!rule_count_res.flag) return showToast(rule_count_res.errMsg)


    item.checked = !item.checked
    checkedList.value.push(item)
    checkedAmt.value += (+item.deductionAmt)
    // console.log('checkedList.value :>> ', checkedList.value);

    // 验证兑换券的使用
    goodsTicketList.value.forEach(v=>{
        if(v.goodsCode == item.goodsCode){
            v.orderQty -= Number(item.goodsCount)
            if(v.orderQty <= 0)
            v.isCanUseMore = false
        }
    })
    
}
// 删除优惠券
const delCoupon = (k) => {
    console.log(checkedList.value);
    console.log(checkedList.value[k]);
    console.log(payListForm.payAmt);
    // payListForm.payAmt = payListForm.payAmt + Number(checkedList.value[k].deductionAmt)
    // ticketValue.value = ticketValue.value - Number(checkedList.value[k].deductionAmt)
    checkedList.value.splice(k, 1);
    ticketValue.value = 0
    // payListForm.payAmt = 0
    // checkedList.value.forEach(item => {
    //     console.log(item.TicketAmt);
    //     // payListForm.payAmt += Number(item.deductionAmt)
    //     ticketValue.value += Number(item.deductionAmt)
    // })
    // 如果有兑换券
    let toolAllAmt = goodsTicketList.value[0].totalPrice //订单总金额
        console.log(toolAllAmt);
        // 计算兑换券的抵扣金额和(8折折扣券的计算金额得先减去兑换券的金额)
        const sum = computed(() => {
            return checkedList.value
                .filter(item => item.TypeCode == '3')  // 过滤出 TypeCode 等于 3 的元素(兑换券)
                .reduce((acc, item) => acc + item.deductionAmt, 0);  // 计算 deductionAmt 总和(兑换券抵扣金额)
        });
        console.log(sum.value);
        
        toolAllAmt = Number(toolAllAmt) - Number(sum.value)
        console.log(toolAllAmt);
        // 计算金额
        checkedList.value.forEach(item => {
            console.log(item.TicketAmt);
            if(item.TypeCode == '2'){
                console.log(item.Discounts);
                // 多张折扣券的计算金额得在之前的基础上打折 如8折后的金额再打8折
                item.deductionAmt = Number(toolAllAmt) * (1 - (Number(item.Discounts)/ 10)) 
                toolAllAmt = toolAllAmt - item.deductionAmt
                console.log(item.deductionAmt);
            }
            ticketValue.value += Number(item.deductionAmt)
        })
    
}
// 取消
const couponCancle = () => {
    showTickets.value = false
    ticketValue.value = 0
    checkedList.value = []
}
// 确定(选择好优惠券后点击确认)
const couponConfirm = () => {
   
        ticketValue.value = 0
        // 如果有兑换券
        let toolAllAmt = cartStore.totalOrderAmt //订单总金额
        console.log(toolAllAmt);
        // 计算兑换券的抵扣金额和(8折折扣券的计算金额得先减去兑换券的金额)
        const sum = computed(() => {
            return checkedList.value
                .filter(item => item.TypeCode == '3')  // 过滤出 TypeCode 等于 3 的元素(兑换券)
                .reduce((acc, item) => acc + item.deductionAmt, 0);  // 计算 deductionAmt 总和(兑换券抵扣金额)
        });
        console.log(sum.value);
        
        toolAllAmt = Number(toolAllAmt) - Number(sum.value)
        console.log(toolAllAmt);
        // 计算金额
        checkedList.value.forEach(item => {
            console.log(item.TicketAmt);
            if(item.TypeCode == '2'){
                console.log(item.Discounts);
                // 多张折扣券的计算金额得在之前的基础上打折 如8折后的金额再打8折
                item.deductionAmt = Number(toolAllAmt) * (1 - (Number(item.Discounts)/ 10)) 
                toolAllAmt = toolAllAmt - item.deductionAmt
                console.log(item.deductionAmt);
            }
            console.log(item.deductionAmt);
            ticketValue.value += Number(item.deductionAmt)
        })
        console.log(ticketValue.value);
    // 如果优惠券超过待付金额
    if(ticketValue.value >= stayPay.value ){
        ticketValue.value = stayPay.value
  
    }
     // 使用优惠券时 要判断是否用了金币和金币的
    if(coinDiko.value >0 && (stayPay.value - coinDiko.value - ticketValue.value)<= 0){ // 使用了金币并且优惠券加上金币超过待支付的金额
        coinDiko.value = 0
        coinsValue.value = 0
        onSelectCoins()
    }
    // emitCoinsSubmit()
    
    showTickets.value = false
    // payListForm.payAmt = payListForm.payAmt - ticketValue.value - coinsValue.value
}
//  ---------------------------------------------------------------- 支付 ------------------------------------------------------
const bookAmtTool = ref({}) // 记录支付信息 给预订押金使用
const onPay = async function () {
    loading.value = true
    postForm.memberTicketCode = checkedList.value.map(item => item.Code).join(',');
    isVip.value = false
    if(memberData.value.memberIsPayCard == 1){
        isVip.value = true
    }
    postForm.isVip = isVip.value
    // postForm.isVip = 
    // 如果使用优惠券或者会员卡（或者两者都有）
    if (checkedList.value.length > 0 || memberPay.value) {
     // 如果使用会员卡
     // if ( memberPay.value) {
        // if (payListForm.payAmt == '') {
        //     console.log(payListForm.payAmt);
        //     showToast('请输入金额')
        //     return
        // } else 
        if (payListForm.payAmt < 0) {
            showToast('支付金额不能为负数')
            loading.value = false
            return
        } else if (Number(payListForm.payAmt) > Number(formatDecimal(showPayAmt.value))) {
            showToast('支付金额超过待支付金额')
            loading.value = false
            return
        } else {
            // console.log('couponChecked.value :>> ', couponChecked.value);
            postForm.payList = []
            // 本条的付款金额
            payListForm.totalAmt = formatDecimal(Number(payListForm.payAmt - payListForm.giveChange))
            // 客人付款金额
            payListForm.payAmt = formatDecimal(Number(payListForm.payAmt))
            // 赋值消费批次号
            postForm.payBatchCode = cartStore.payBatchCode
            // 点单商品金额
            postForm.orderAmt = cartStore.totalOrderAmt
            // 实际付款金额
            postForm.realPayAmt = payListForm.payAmt
            // 支付列表
            postForm.payList.push(payListForm)
            postForm.payType = '004'
            payListForm.payType = '004'
            console.log(postForm);

            // console.log('---------')
            // console.log(postForm)
            let orderInfo = ls.get('ORDER_INFO')
            if (orderInfo && orderInfo.dataList) {
                postForm.detailList = orderInfo.dataList.map(obj => obj.itemCode).join(',')
            }
            await payOrder(postForm)
            // if (ls.get('PAY_TYPE') == 1) {
            //     // 先下单 再买单
            //     const orderForm = ls.get('ORDER_FORM')
            //     console.log(orderForm);
            //     // 如果已经有买过的单 点单就要传orderBatchCode
            //     // if (ls.get('ORDER_BATCH_CODE')) {
            //     //     orderForm.orderBatchCode = ls.get('ORDER_BATCH_CODE')
            //     // }
            //     calculateOrderQty(orderForm.detail)
            //     await Api.Common.AppObjProcess.Do({
            //         "functionName": "orderAdd",
            //         "contentData": orderForm
            //     }).then(async res => {
            //         console.log(res);
            //         cartStore.orderBatchCode = res.orderBatchCode
            //         ls.set('ORDER_BATCH_CODE', res.orderBatchCode)
            //         cartStore.goodsOrderStr = res.dataList.map(obj => obj.itemCode).join(',');
            //         postForm.detailList = cartStore.goodsOrderStr
            //         onCancelOrderForm.value.itemCodeList = cartStore.goodsOrderStr
            //         await payOrder(postForm)
            //     }).catch(err=>{
            //         loading.value = false
            //     })
            // } else {
            //     await payOrder(postForm)
            // }
        }
    }
    // 金币支付
    if (coinsValue.value > 0) {
        postForm.payList = []
        // 本条的付款金额
        payListForm.totalAmt = payListForm.payAmt - payListForm.giveChange
        // 客人付款金额
        payListForm.payAmt = formatDecimal(Number(coinDiko.value))
        // 赋值消费批次号
        postForm.payBatchCode = cartStore.payBatchCode
        // 点单商品金额
        postForm.orderAmt = cartStore.totalOrderAmt
        // 实际付款金额
        postForm.realPayAmt = coinsValue.value
        // 支付列表
        postForm.payList.push(payListForm)
        postForm.payType = '013'
        console.log(postForm);

        // console.log('---------')
        // console.log(postForm)
        await payOrder(postForm)
        // if (ls.get('PAY_TYPE') == 1) {
        //     // 先下单 再买单
        //     const orderForm = ls.get('ORDER_FORM')
        //     console.log(orderForm);
        //     // 如果已经有买过的单 点单就要传orderBatchCode
        //     // if (ls.get('ORDER_BATCH_CODE')) {
        //     //     orderForm.orderBatchCode = ls.get('ORDER_BATCH_CODE')
        //     // }
        //     calculateOrderQty(orderForm.detail)
        //     await Api.Common.AppObjProcess.Do({
        //         "functionName": "orderAdd",
        //         "contentData": orderForm
        //     }).then(async res => {
        //         ls.remove('PAY_TYPE')
        //         console.log(res);
        //         cartStore.orderBatchCode = res.orderBatchCode
        //         ls.set('ORDER_BATCH_CODE', res.orderBatchCode)
        //         cartStore.goodsOrderStr = res.dataList.map(obj => obj.itemCode).join(',');
        //         postForm.detailList = cartStore.goodsOrderStr
        //         onCancelOrderForm.value.itemCodeList = cartStore.goodsOrderStr
                
        //         await payOrder(postForm)
        //     }).catch(err=>{
        //         loading.value = false
        //     })
        // } else {
        //     await payOrder(postForm)
        // }
        
    }
    console.log(bookAmt.value);
    
    if(bookAmt.value > 0){
            let obj = {
            cardNo : bookCardNo.value,
            tradeNo : bookTradeNo.value,
            payType : bookPayType.value,
            payAmt : bookAmt.value,
            totalAmt : bookAmt.value,
            isReservePay:'1'
            }
            postForm.payList = [obj]
            postForm.payType = bookPayType.value
            postForm.realPayAmt = bookAmt.value
            postForm.tradeNo = bookTradeNo.value
            bookAmtTool.value = postForm
            console.log('bookAmtTool.value',bookAmtTool.value);
           
            bookAmtTool.value.payBatchCode = ls.get('PAY_BATCH_CODE')
            payOrder(bookAmtTool.value)
            bookAmt.value = 0
        
    }
}
const sendAmtForm = ref({
  amt:'' ,// 当前订单金额
  payAmt:'', // 本次支付金额
  cardNo:'' ,// 会员卡号
  isVipPay:'' ,// 是否会员权益支付 0 否 1是
  goods:'' ,// 商品信息
})
const payPreAmtRate = ref(0)

// 取消订单的参数
const onCancelOrderForm = ref({
  payBatchCode: '', // 如果已经卖过单,就只要传payBatchCode就行
  itemCodeList: ''
})
function formatNumber (num) {
  if (num) {
    return num.toFixed(2)
  } else {
    return 0
  }
}

// 结账
const checkOutForm = ref({
  payBatchCode: '',
  itemCodeList: ''
})

const doCheckOut = ()=>{
    checkOutForm.value.payBatchCode = cartStore.payBatchCode
    checkOutForm.value.itemCodeList = postForm.detailList
    const toolConsumeCode = ls.get('TABLE_INFO').consumeCode 
              Api.Common.AppObjProcess.Do({
                functionName: 'Checkout',
                contentData: checkOutForm.value
              }).then(res => {
                showToast(res.result)
                ls.remove('ORDER_BATCH_CODE')
                ls.remove('PAY_BATCH_CODE')
                ls.remove('TABLE_INFO')
                ls.remove('MEMBER_CARD_NUMBER')
                ls.remove('PAY_INFO')
                ls.remove('CART_LIST')
                ls.remove('ORDER_FORM')
                ls.remove('PAY_TYPE')
                ls.remove('ROOM_DETAIL')
                router.replace('/open')
                cartStore.payAmt = 0
                cartStore.realPayAmt = 0
                cartStore.totalOrderAmt = 0
                cartStore.giveChange = 0
                cartStore.smallChange = 0
                cartStore.payBatchCode = ''
                cartStore.ClearState()
                showToast('支付完成')
                // cartStore.discountAmt = 0
                setTimeout(() => {
                  Api.Common.AppObjProcess.Do({
                  functionName: 'OrderPayPrint',
                  contentData: { consumeCode: toolConsumeCode, payBatchCode: checkOutForm.value.payBatchCode, isAdd: IsAdd.value }
                  }).then(res => {
                    console.log(res);
                    loading.value = false
                  })
                }, 800);
               
              })
}



const payOrder = async (obj) => {
    const form = JSON.parse(JSON.stringify(obj))
    if(form.payList.some(item => item.payType === '004' && item.payAmt != 0  )){
        const foundElement = form.payList.find(item => item.payType === '004' && item.payAmt != 0);
        if(foundElement){
            sendAmtForm.value.payAmt = foundElement.payAmt
        }
        if(form.serviceAmt.some(item => item.type === "会员折扣优惠" )){
            const foundEl = form.serviceAmt.find(item => item => item.type === "会员折扣优惠");
            sendAmtForm.value.amt  = formatNumber(form.orderAmt - foundEl.amt)
        }else{
            sendAmtForm.value.amt  = formatNumber(form.orderAmt)
        }
        
        sendAmtForm.value.goods = JSON.stringify(orderInfo.value)
        sendAmtForm.value.isVipPay = form.isVip ? '1':'0'
        sendAmtForm.value.cardNo = memberData.value.code
        
        console.log(sendAmtForm.value)
        console.log(form,'formformformformformformform');
        await Api.Common.AppObjProcess.Do({
          functionName: 'GetPrePayAmt',
          contentData: sendAmtForm.value
        }).then(res=>{
            console.log(res);
            console.log(res.payPreAmt);
            payPreAmtRate.value = res.payPreAmtRate
            let mempay = form.payList.find(item => item.payType === '004' && item.payAmt != 0);
            if (mempay) {
                mempay.prePayAmt = res.payPreAmt; 
                mempay.payPreAmtRate = payPreAmtRate.value
                // 会员卡余额支付 分配给会员卡余额和赠送金额
                if(mempay.prePayAmt >= mempay.payAmt){
                    mempay.prePayAmt = mempay.payAmt
                    mempay.payAmt = 0
                }else{
                    mempay.payAmt = Number(formatDecimal(mempay.payAmt - mempay.prePayAmt))
                }
                
            } 
            
        }).catch(err=>{
            console.log(err);
            loading.value = false
        })

    }

    await Api.Common.AppObjProcess.Do({
        "functionName": "orderPay",
        "contentData": form
    }).then(async (res) => {
        console.log(res)
        // 存 - 消费批次号
        cartStore.payBatchCode = res.payBatchCode
        ls.set('PAY_BATCH_CODE', res.payBatchCode)
        // 存 - 已付金额
        cartStore.payAmt = res.alreadyPayAmt
        // cartStore.giveChange = res.giveChange
        // cartStore.smallChange = res.smallChange
        // 刷新会员数据
        // getMemberInfo()
        ls.remove('PAY_TYPE')
        // 判断是否支付完成
        // cartStore.unpaid
        if (cartStore.unpaid == 0) {
           
            doCheckOut()
            // await cartStore.ClearState()
            // ls.remove('PAY_BATCH_CODE')
            // ls.remove('TABLE_INFO')
            // ls.remove('MEMBER_CARD_NUMBER')
            // ls.remove('CART_LIST')
            // ls.remove('PAY_INFO')
            // setTimeout(() => {
            //     // return
            //     if (router.currentRoute.value.path == '/open/orderMember') {
            //         router.back()
            //     }
            // }, 2000);
            // return
        } else {
            loading.value = false
            // 开启继续支付弹窗
            if (!payShow.value) {
                payShow.value = true
            }
        }
        
    }).catch(err=>{
        loading.value = false
        if(ls.get('PAY_TYPE') == 1){
            Api.Common.AppObjProcess.Do({
                functionName: 'OrderCancelV2',
                contentData: onCancelOrderForm.value
            }).then(async res => {
                // showToast('支付失败，订单取消')
                // await cartStore.ClearState()
                ls.remove('ORDER_BATCH_CODE')
                ls.remove('PAY_BATCH_CODE')
                // ls.remove('TABLE_INFO')
                // ls.remove('MEMBER_CARD_NUMBER')
                // ls.remove('PAY_INFO')
                // ls.remove('PAY_TYPE')
                // ls.remove('ORDER_FORM')
                // ls.remove('ROOM_DETAIL')
                // cartStore.ClearState()
                // router.replace('/open')
            })
        }
    })
}
// 继续支付
const onContinueToPay = function () {
    router.replace('/open/orderCashier')
    payShow.value = false
    // 付款金额赋值
    payListForm.payAmt = formatDecimal(cartStore.unpaid)
}

const onCheckDiscount = () => {
    showToast('当前版本暂不支持使用')
}

// 获取买单记录（已买单）
const getBuyRecord = () => {
    if (cartStore.orderBatchCode == '') {
        cartStore.orderBatchCode = ls.get('ORDER_BATCH_CODE')
    }
    if (cartStore.payBatchCode == '') {
        cartStore.payBatchCode = ls.get('PAY_BATCH_CODE')
    }
    if (cartStore.tableInfo.roomName == '') {
        cartStore.tableInfo = ls.get('TABLE_INFO')
    }
    Api.Common.AppObjProcess.Do({
        "functionName": "getOrderPayNew",
        "contentData": {
            roomCode: cartStore.tableInfo.roomCode,
            consumeCode: cartStore.tableInfo.consumeCode,
            payBatchCode: cartStore.payBatchCode
        }
    }).then(res => {
        console.log('接口获取商品', res)
        cartStore.totalOrderAmt = res.totalOrderAmt
        cartStore.payAmt = res.payAmt
        // cartStore.realPayAmt = res.realAmt
        cartStore.giveChange = res.giveChange
        selectWares.value = res.dtOrder
        // cartStore.smallChange = res.smallChange
        postForm.detailList = res.detailList
        orderInfo.value = res.dtOrder
        console.log(orderInfo.value,'orderInfo.value');
        postForm.consumeCode = cartStore.tableInfo.consumeCode
        postForm.roomCode = cartStore.tableInfo.roomCode
        postForm.waiterUserCode = cartStore.tableInfo.waiterUserCode
        payListForm.totalAmt = cartStore.unpaid
        payListForm.payAmt = formatDecimal(Number(cartStore.unpaid))
        stayPay.value = payListForm.payAmt
        toolPayAmt.value = payListForm.payAmt
        // coinsTotal.value = 0
        // console.log(2222)
        // selectWares.value.forEach(item => {
        //     if (memberData.value.isPayCard == "1" && item.isUseGold == '1') {
        //         coinsTotal.value += Number(item.salePrice) * Number(item.num)
        //     } else if (memberData.value.isPayCard != "1" && item.isUseGold == '1') {
        //         coinsTotal.value += Number(item.vipPrice) * Number(item.num)
        //     }
        // });
    })
}

const canChange = ref(true) // 是否可以切换会员卡
const isVip = ref(false) // 是否是权益会员
// 获取会员信息
const getMemberInfo = () => {
    if (cartStore.account == '') {
        cartStore.account = ls.get('MEMBER_CARD_NUMBER')
    }
    Api.Common.AppObjProcess.Do({
        "functionName": "GetMemberInfo",
        "contentData": {
            code: cartStore.account
        }
    }).then(res => {
        console.log('获取会员信息', res);
        if(!configStore.shopInfo.isUseBrandCard){
            res.result = res.result.filter(card => card.cardType != 1);
        }
        memberDataList.value = res.result
        const r = res.result[0]
        memberData.value = r
        console.log(memberData.value);
        payListForm.cardNo = r.code
        payListForm.memberName = r.name
        payListForm.memberMobile = r.mobile
        if (res.result.length <= 1) {
            canChange.value = false
        }
        // memberIsPayCard  1 升级
    })
}
// 会员卡信息
const cardChange = (k) => {   // 1 品牌卡 2门店卡
    let cardId = memberDataList.value.findIndex(item => item.cardType == 1) // 品牌卡下标
    let storeCardId = memberDataList.value.findIndex(item => item.cardType == 2) // 门店卡下标

    if (k == 1) {
        memberData.value = memberDataList.value[storeCardId]

    } else {
        memberData.value = memberDataList.value[cardId]
    }
    payListForm.cardNo = memberData.value.code
    console.log(memberData.value);
}

let serveAmt = ref(0) // 优惠金额（其它项目）
const totalSelectedMoney = (() => {
    let sum = 0;
    postForm.serviceAmt.forEach((item, index) => {
        if (item.type != "服务费") {
            sum += Number(item.amt);
        } else {
            sum -= Number(item.amt);
        }
    })
    serveAmt.value = Number(sum);
});
const isUseVipPrice = ref(false) // 是否使用vip价格


onMounted(async()=>{
    // 预订押金
    getBookAmt()
})

const bookAmt = ref(0)
const toolBookAmt= ref(0)
const bookPayType = ref('')
const bookCardNo = ref('')
const bookTradeNo = ref('')
const orderInfo = ref([])
const getBookAmt = async()=>{
// 预订押金
await Api.Common.AppObjProcess.Do({ "functionName": "GetRoomReserveState", "contentData": {roomCode:cartStore.tableInfo.roomCode} })
    .then(res => {
        if(!res.isUseReserveAmt && res.reserveAmt > 0){ //true 已抵扣 false 未抵扣  false可以用
          bookAmt.value = res.reserveAmt
          toolBookAmt.value = res.reserveAmt
          bookPayType.value = res.posPayType
          bookCardNo.value = res.cardNo
          bookTradeNo.value = res.tradeNo
          stayPay.value = stayPay.value - res.reserveAmt
          console.log(res);
          // this.data.carPrice = this.data.carPrice - res.reserveAmt
        }else{
          bookAmt.value = 0
        }
    })
    .catch(err=>{
    })
}
let IsAdd = ref(false)
// 初始化
const onInit = () => {
    getMemberInfo() // 获取会员信息
    // 获取优惠信息
    if (ls.get('SERVICE_AMT')) {
        postForm.serviceAmt = ls.get('SERVICE_AMT')
        const hasDiscount = postForm.serviceAmt.some(item => item.type === "会员折扣优惠");
        console.log(hasDiscount);
        if (hasDiscount) {
            isUseVipPrice.value = true
        }
        console.log(postForm.serviceAmt);
        totalSelectedMoney()
    }
    if (ls.get('PAY_TYPE') == 1 || ls.get('PAY_TYPE') == 2) {
        IsAdd.value = true
        console.log("ls.get('CART_LIST')", ls.get('CART_LIST'));
        const array = ls.get('CART_LIST')
        let total = 0;
        let vipTotal = 0
        // 计算满足条件的元素的 orderQty * salePrice 的总和
        console.log(1111)
        array.forEach(item => {
            console.log('item :>> ', item);
            total += item.num * item.salePrice;
            vipTotal += item.num * item.vipPrice
        });
        console.log(' coinsTotal.value:>> ', coinsTotal.value);
        cartStore.totalOrderAmt = total // 总价格
        // cartStore.vipOrderAmt = vipTotal // vip价格
        payListForm.payAmt = Number(total) - serveAmt.value
        toolPayAmt.value = payListForm.payAmt
        stayPay.value = payListForm.payAmt
        cartStore.orderBatchCode = ls.get('ORDER_BATCH_CODE')
        const itemCodeForm = ls.get('ORDER_FORM')
        orderInfo.value = ls.get('ORDER_FORM').detail
        console.log(orderInfo.value,'orderInfo.value');
        
        selectWares.value = itemCodeForm.detail.filter(item => item.itemType != '3')

        console.log(itemCodeForm);
        // 将商品itemCode赋值给postForm.detailList
        postForm.detailList = itemCodeForm.detail.map(obj => {
            if (obj.itemType == '2' && Array.isArray(obj.goodsInfoDetail)) {
                const itemCodes = obj.goodsInfoDetail.map(item => item.itemCode);
                return [...itemCodes, obj.itemCode].join(',');
            } else {
                return obj.itemCode;
            }
        }).join(',');
    } else {
        getBuyRecord()
    }

    cartStore.tableInfo = ls.get('TABLE_INFO')
    postForm.consumeCode = cartStore.tableInfo.consumeCode
    postForm.roomCode = cartStore.tableInfo.roomCode
    postForm.payUser = cartStore.tableInfo.waiterUserCode

}
onInit()

// ----------------------金币-----------------------
const coinsValue = ref(0)
let CoinsVisible = ref(false)
const CoinsRef = ref()
// 打开弹窗
const onSelectCoins = (name) => {
    coinsTotal.value = 0
    // 可能有点商品可以用金币 有点商品不能用金币 使用不能直接用待付金额
    selectWares.value.forEach(item=>{
        if (memberData.value.memberIsPayCard == "0" && item.isUseGold == '1') {
            coinsTotal.value += Number(item.salePrice) * Number(item.orderQty)
        } else if (memberData.value.memberIsPayCard == "1" && item.isUseGold == '1') {
            coinsTotal.value += Number(item.vipPrice) * Number(item.orderQty)
        }
    })
    coinsTotal.value = coinsTotal.value - serveAmt.value - cartStore.payAmt - ticketValue.value // 减去优惠价格、已付金额、优惠券优惠金额 (serveAmt.value包括会员价优惠)
 
    CoinsVisible.value = true

    // nextTick(() => {
    //   const data = {
    //     user: user.re,
    //     currentCard: currentCard.value,
    //     activeName: name
    //   }
    //   SendRef.value.open(data)
    // });
}
// 取消表格弹窗
const emitCoinsCancel = (params) => {
    console.log(params)
    CoinsVisible.value = false
}

// 提交表格弹窗
const emitCoinsSubmit = (params) => {
    console.log(params)
    const { checked } = params
    if (checked == true) {
        coinsValue.value = coinsTotal.value
        // payListForm.payAmt = payListForm.payAmt - coinsValue.value
    } else if ( checked == 'bugo') {
        coinsValue.value = memberData.value.currentCoins
    }else{
        coinsValue.value = 0
    }
    coinDiko.value = coinsValue.value
    CoinsVisible.value = false

}

</script>
<style scoped lang="scss">
.orderMember-container {
    display: flex;
    flex-direction: column;
    min-height: 100%;
    overflow-y: scroll;
    padding: 0 12px;
}

::v-deep(.van-checkbox__label) {
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 16px;
    color: #FFFFFF;
}

.orderMember-main {
    flex-grow: 1;

    .orderMember-card {
        margin-top: 10px;
        background-image: url('@/assets/images/open/i_member_card.png');
        background-repeat: no-repeat;
        background-size: 100% 100%;
        font-size: 0;
        width: 351px;
        height: 180px;
        position: relative;

        &-corner {
            display: flex;
            justify-content: space-between;

            .card-corner-no {
                background: #ECDEB4;
                border-radius: 8px 0px 10px 0px;
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #806A40;
                line-height: 12px;
                padding: 4px 10px;
            }

            .card-header-change {
                margin: 4px 4px 0 0;
                width: 90px;
                height: 20px;
                background: linear-gradient(90deg, #FF3333, #FF8833);
                border-radius: 10px;
                font-family: PingFang SC;
                font-weight: 500;
                font-size: 12px;
                line-height: 20px;
                color: #FFFFFF;
                text-align: right;
                padding-right: 5px;
                position: relative;

                .icon {
                    position: absolute;
                    left: 10px;
                    top: 5px;
                    width: 10px;
                    height: 10px;
                    background-image: url('@/assets/svg/member/v_member-change.png');
                    background-position: center;
                    background-size: cover;
                    background-repeat: no-repeat;
                }

            }
        }

        &-heading {
            display: flex;
            align-items: center;
            padding: 12px 0 0 20px;

            &__name {
                font-size: 18px;
                font-family: PingFang SC;
                font-weight: bold;
                color: #80590D;
                line-height: 18px;
            }

            &__level {
                display: block;
                width: 60px;
                height: 22px;
                margin-left: 8px;
            }
        }

        &-money {
            padding: 15px 0 0px 20px;

            &__num {
                font-size: 20px;
                font-family: PingFang SC;
                font-weight: bold;
                color: #B35900;
                line-height: 20px;
            }

            &__label {
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #B39559;
                line-height: 12px;
                padding-top: 8px;
                position: relative;
                .value-icon{
                    width: 13px;
                    height: 13px;
                    position: absolute;
                    left: 55px;
                    bottom: -2px;
                    background-image: url('@/assets/svg/member/v_member-icon.png');
                    background-position: center;
                    background-size: contain;
                    background-repeat: no-repeat;
                }
                .showAmt{
                    width: 150px;
                    height: 106px;
                    position: absolute;
                    left: 50px;
                    bottom: 10px;
                    z-index: 990;
                    background-image: url('@/assets/images/member/i_back-amt.png');
                    background-position: center;
                    background-size: contain;
                    background-repeat: no-repeat;
                    padding: 12px;
                    .showAmt-top{
                        padding-bottom: 10px;
                        .showAmt-top-value{
                        color: #FFFFFF;
                        padding-bottom: 8px;
                        }
                    }
                    .showAmt-main{
                        text-align: left;
                        .showAmt-main-value{
                        padding-bottom: 8px;
                        }
                    }
                }
            }
        }

        &-line {
            margin: 10px 20px 0;
            height: 1px;
            background: #CCB88F;
        }

        &-footer {
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            padding-bottom: 20px;
            display: flex;

            &-item {
                flex: 1;
                text-align: center;
                border-right: 1px solid #CCB88F;
            }

            &__num {
                font-size: 14px;
                font-family: PingFang SC;
                font-weight: bold;
                color: #806A40;
                line-height: 14px;
            }

            &__label {
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #B39559;
                line-height: 12px;
                margin-top: 5px;
               
            }
        }
    }

    .orderMember-card1 {
        margin-top: 10px;
        background-image: url('@/assets/images/open/i_member_card1.png');
        background-repeat: no-repeat;
        background-size: 100% 100%;
        font-size: 0;
        // width: 351px;
        height: 180px;
        position: relative;

        &-corner {
            display: flex;
            justify-content: space-between;

            .card1-corner-no {
                background: #DB230F;
                border-radius: 8px 0px 10px 0px;
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #FFFFFF;
                line-height: 12px;
                padding: 4px 10px;
            }

            .card1-header-change {
                margin: 4px 4px 0 0;
                width: 90px;
                height: 20px;
                background: linear-gradient(0deg, #E9CDA4, #F4EECF);
                border-radius: 10px;
                font-family: PingFang SC;
                font-weight: 500;
                font-size: 12px;
                line-height: 20px;
                color: #312203;
                text-align: right;
                padding-right: 5px;
                position: relative;

                .icon {
                    position: absolute;
                    left: 10px;
                    top: 5px;
                    width: 10px;
                    height: 10px;
                    background-image: url('@/assets/svg/member/v_member-change1.png');
                    background-position: center;
                    background-size: cover;
                    background-repeat: no-repeat;
                }

            }
        }

        &-heading {
            display: flex;
            align-items: center;
            padding: 12px 0 0 20px;

            &__name {
                font-size: 18px;
                font-family: PingFang SC;
                font-weight: bold;
                color: #FFFFFF;
                line-height: 18px;
            }

            &__level {
                display: block;
                width: 60px;
                height: 22px;
                margin-left: 8px;
            }
        }

        &-money {
            padding: 15px 0 0px 20px;

            &__num {
                font-size: 20px;
                font-family: PingFang SC;
                font-weight: bold;
                color: #FFFFFF;
                line-height: 20px;
            }

            &__label {
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #FFE5E5;
                line-height: 12px;
                padding-top: 8px;
                position: relative;
                .value-icon{
                    width: 13px;
                    height: 13px;
                    position: absolute;
                    left: 55px;
                    bottom: -2px;
                    background-image: url('@/assets/svg/member/v_member-icon.png');
                    background-position: center;
                    background-size: contain;
                    background-repeat: no-repeat;
                }
                .showAmt{
                    width: 150px;
                    height: 106px;
                    position: absolute;
                    left: 50px;
                    bottom: 10px;
                    z-index: 990;
                    background-image: url('@/assets/images/member/i_back-amt.png');
                    background-position: center;
                    background-size: contain;
                    background-repeat: no-repeat;
                    padding: 12px;
                    .showAmt-top{
                        padding-bottom: 10px;
                        .showAmt-top-value{
                        color: #FFFFFF;
                        padding-bottom: 8px;
                        }
                    }
                    .showAmt-main{
                        text-align: left;
                        .showAmt-main-value{
                        padding-bottom: 8px;
                        }
                    }
                }
            }
        }

        &-line {
            margin: 10px 20px 0;
            height: 1px;
            background: #E65C5C;
        }

        &-footer {
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            padding-bottom: 20px;
            display: flex;

            &-item {
                flex: 1;
                text-align: center;
                border-right: 1px solid #E65C5C;
            }

            &__num {
                font-size: 14px;
                font-family: PingFang SC;
                font-weight: bold;
                color: #990000;
                line-height: 14px;
            }

            &__label {
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #CC2929;
                line-height: 12px;
                margin-top: 5px;
            }
        }
    }

    .orderMember-form {

        &-heading {
            padding-top: 30px;
            font-size: 12px;
            font-family: PingFang SC;
            font-weight: 500;
            color: #CCCCCC;
            line-height: 12px;

            &__highlight {
                color: #FFAA00;
            }
        }

        &-recharge {

            &__title {
                padding-top: 30px;
                font-size: 13px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #CCCCCC;
                line-height: 13px;
            }

            &__item {
                padding: 10px 0;
                display: flex;
                justify-content: space-between;
                align-items: flex-end;
                align-items: center;
                border-bottom: 1px solid #4D4D4D;
            }

            &__rmb {
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: bold;
                color: #FFFFFF;
                line-height: 12px;
                padding-top: 10px;
            }

            &__input {
                // margin: 0 36px;
                background: #383840;
                // background: red;
                border-radius: 4px;
                font-size: 24px;
                font-family: PingFang SC;
                font-weight: bold;
                color: #FFFFFF;
                line-height: 24px;
                display: block;
                width: 100%;
                // flex: 1;
                // padding-left: 20px;
                padding: 8px 0 8px 20px;

                &::placeholder {
                    font-size: 24px;
                }
            }

            &__btn {
                background: #5C5C66;
                border-radius: 4px;
                padding: 9px 17px;
                font-size: 14px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #FFFFFF;
                line-height: 14px;
            }
        }

        &-radio {

            // filter: grayscale(100%);
            .radio-coupon {
                display: flex;
                align-content: center;
                justify-content: space-between;
                padding-top: 15px;
                padding-bottom: 15px;
                // margin-bottom: 20px;
                border-bottom: 1px solid #383840;
                ;

                .ticket-box {
                    font-family: PingFang SC;
                    font-weight: 500;
                    font-size: 16px;
                    color: #FFFFFF;
                    display: flex;
                    align-items: center;

                    .img-ticket {
                        width: 30px;
                        height: 30px;
                        margin-right: 10px;
                    }
                }
            }



            .radio-coupon-list {
                display: flex;
                align-content: center;
                justify-content: space-between;
                padding: 0 64px 0 34px;
                margin-top: 15px;
                // margin-bottom: 16px;

                .list-item {
                    font-family: PingFang SC;
                    font-weight: 500;
                    font-size: 12px;
                    color: #666666;
                    line-height: 12px;
                }

                .list-icon {
                    font-family: PingFang SC;
                    font-weight: 500;
                    font-size: 12px;
                    color: #999999;
                    line-height: 12px;
                    padding: 0 10px
                }
            }



            :deep(.orderMember-form-radio-item) {
                // padding-top: 25px;
                align-items: center;

                &:first-child {
                    // padding-top: 29px;
                }

                .van-radio__label {
                    font-size: 16px;
                    font-family: PingFang SC;
                    font-weight: 500;
                    color: #FFFFFF;
                    line-height: 16px;
                    margin-left: 6px;
                    display: flex;
                    align-items: center;
                }
            }

            &__icon {
                width: 16px;
                height: 16px;
                vertical-align: -2px;
            }

            &__select {
                border-radius: 2px;
                padding: 7px 29px 7px 12px;
                background: #28282E;
                margin-left: 6px;
                position: relative;
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #FFCC66;
                line-height: 12px;

                &:after {
                    content: '';
                    position: absolute;
                    right: 12px;
                    top: 0;
                    width: 12px;
                    height: 100%;
                    background-image: url('@/assets/svg/common/v_triangle_orange.svg');
                    background-repeat: no-repeat;
                    background-size: 12px auto;
                    background-position: center center;
                }
            }
        }
    }

    .radio-input {
        padding: 0px 0px 0px;
        position: relative;

        .radio-input-icon {
            position: absolute;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 12px;
            color: #FFFFFF;
            left: 6px;
            top: 20px;
        }

        .radio-input-yuan {
            position: absolute;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 14px;
            color: #CCCCCC;
            right: 12px;
            top: 12px;
        }

        .radio-input-title {
            padding-top: 10px;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 12px;
            color: #CCCCCC;

            .spe {
                color: #FFAA00;
            }
        }
    }
}

.orderMember-footer {
    position: relative;
    bottom: 0;
    padding-bottom: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .orderMember-footer-value {
        font-family: PingFang SC;
        font-weight: bold;
        font-size: 12px;
        color: #CCCCCC;
        line-height: 12px;

        .value-icon {
            color: #FFAA00
        }

        .value-money {
            font-size: 18px;
            color: #FFAA00
        }
    }
}

.orderMember-form-radio__popover {
    :deep(.van-popover__arrow) {
        color: #333340;
    }

    :deep(.van-popover__content) {
        background-color: #333340;
        font-size: 14px;
        color: #FFCC66;
        width: 160px;
    }

    :deep(.van-popover__action) {
        height: 47px;
        padding: 0 9px;
        width: 100%;
    }
}

.popup-pay {
    width: 300px;
    text-align: center;
    padding-bottom: 20px;

    &-title {
        padding-top: 20px;
        text-align: center;
        font-size: 18px;
        font-family: PingFang SC;
        font-weight: bold;
        color: #FFFFFF;
        line-height: 18px;
    }

    &-unpaid {
        padding-top: 20px;
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #CCCCCC;
        line-height: 16px;
    }

    &__hightlight {
        color: #FFAA00;
        padding-top: 20px;
    }

    &-success {
        font-size: 18px;
        font-family: PingFang SC;
        font-weight: bold;
        color: #FFFFFF;
        line-height: 18px;
        padding-top: 45px;
    }

    &-control {
        width: 120px;
        margin: auto;

        &.goon {
            padding-top: 30px;
        }

        &.finish {
            padding-top: 40px;
        }
    }
}

.showTickets {
    .showTickets-list {
        padding: 10px 12px;
        // max-height: 375px;
        height: 40vh;
        overflow: auto;

        .showTickets-list-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #393940;
            border-radius: 8px;
            margin-bottom: 10px;

            &.canNotUse {
                background-repeat: no-repeat;
                background-position: center;
                background-size: 100%;
                background-image: url('@/assets/images/member/i_coupon_payNotuse.png');
                filter: grayscale(100%);
            }

            .item-left {
                display: flex;
                align-items: center;

                background-repeat: no-repeat;
                background-position: center;
                background-size: 100%;
                width: 300px;
                height: 80px;
                border-radius: 8px;
                position: relative;

                &.huang {
                    background-image: url('@/assets/images/member/i_coupon_payHuang.png');
                }

                &.zhe {
                    background-image: url('@/assets/images/member/i_coupon_payZhe.png');
                }

                &.you {
                    background-image: url('@/assets/images/member/i_coupon_payYou.png');
                }

                .coupon-left {
                    text-align: center;
                    padding: 17px 13px 12px 15px;

                    .coupon-left-title {
                        font-family: PingFang SC;
                        font-weight: bold;
                        font-size: 14px;
                        color: #212121;
                        line-height: 14px;
                        padding-bottom: 8px;
                    }

                    .coupon-left-value {
                        font-family: PingFang SC;
                        font-weight: bold;
                        font-size: 14px;
                        color: #FF3333;
                        line-height: 14px;
                        width: 70px;

                    }
                }

                .coupon-center {
                    padding-left: 13px;

                    .coupon-center-top {
                        font-family: PingFang SC;
                        font-weight: 500;
                        font-size: 12px;
                        color: #666666;
                        line-height: 12px;
                        padding-bottom: 9px;
                    }

                    .coupon-center-center {
                        font-family: PingFang SC;
                        font-weight: bold;
                        font-size: 16px;
                        color: #212121;
                        line-height: 16px;
                        padding-bottom: 8px;
                    }

                    .coupon-center-bottom {
                        font-family: PingFang SC;
                        font-weight: 500;
                        font-size: 12px;
                        color: #996600;
                        line-height: 12px;
                    }
                }

                .coupon-right {
                    position: absolute;
                    top: 0;
                    right: 0;
                    width: 24px;
                    height: 16px;
                    background-image: url('@/assets/images/member/i_coupon_payNew.png');
                    background-repeat: no-repeat;
                    background-position: center;
                    background-size: 100%;
                }
            }

            .item-right {
                .orderMember-form-radio__icon {
                    width: 16px;
                    height: 16px;
                    // vertical-align: -2px;
                    margin-right: 12px;
                }
            }
        }
    }

    .showTickets-bottom {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        background: #0C0C0E;
        padding: 9px 12px 12px 0;
        z-index: 999;

        .showTickets-bottom-cancle {
            width: 120px;
            height: 40px;
            border-radius: 20px;
            border: 1px solid #999999;
            font-family: PingFang SC;
            font-weight: bold;
            font-size: 18px;
            color: #CCCCCC;
            line-height: 40px;
            text-align: center;
        }

        .showTickets-bottom-confirm {
            width: 120px;
            height: 40px;
            background: linear-gradient(0deg, #CCA67A, #FFF4D9);
            border-radius: 20px;
            font-family: PingFang SC;
            font-weight: bold;
            font-size: 18px;
            color: #260C04;
            line-height: 40px;
            text-align: center;
            margin-left: 10px;
        }
    }
}

.orderMember-form-radio {
    margin-top: 20px;
    background: #28282E;
    border-radius: 8px;
    padding: 0 5px 15px 12px
}

.stay-box {
    padding-right: 15px;
    text-align: right;
    margin-top: 15px;
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 12px;
    color: #999999;
}

.font-size-18 {
    font-size: 18px;
}

.color-FFAA00 {
    color: #FFAA00;
}

.usevip-box {
    margin: 20px 0;
}
</style>